<?php

class Controller_Mobile_Fenxiao extends Stourweb_Controller
{
    private $_member;
    private $_level_num=3;
    private $_fenxiao;
    public function before()
    {

        parent::before();
        Common::before_header();
        $member_info = Model_Member_Login::check_login_info();
        $member_info = Model_Member::get_member_byid($member_info['mid']);
        if(empty($member_info))
        {
            Common::message(array('message' => __('unlogin'), 'jumpUrl' => $this->cmsurl . 'member/login'));
        }
        $this->_member=$member_info;
        $fenxiao = DB::select()->from('fenxiao')->where('memberid','=',$member_info['mid'])->execute()->current();
        $fenxiao['fxrank_name'] = Model_Fenxiao_Rank::get_name($fenxiao['fxrankid']);
        $this->_fenxiao = $fenxiao;
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $this->_level_num = $level_num==2?2:3;

        $this->assign('level_num',$this->_level_num);
        $this->assign('fenxiao',$this->_fenxiao);
        $this->assign('member',$this->_member);
    }
    public function action_index()
    {
        $fenxiao=Model_Fenxiao::check_fenxiao($this->_member['mid'],true);

        $total_profit=$this->get_total_profit();
        $unfinish_profit = $this->get_total_unfinish_profit();
        $total_profit+=$unfinish_profit;

        $order_num = $this->get_order_number();
        $fx_member_num = $this->get_member_num(0);
        $member_num = $this->get_member_num(1);

        $this->assign('total_profit',$total_profit);
        $this->assign('unfinish_profit',$unfinish_profit);
        $this->assign('order_num',$order_num);
        $this->assign('fx_member_num',$fx_member_num);
        $this->assign('member_num',$member_num);
        $this->display('../mobile/fenxiao/index');
    }

    //我的订单
    public function action_order()
    {
        $products = Model_Fenxiao::get_fenxiao_product();
        $status_names = Model_Member_Order::$order_status;
        $this->assign('products',$products);
        $this->assign('status_names',$status_names);
        $this->display('../mobile/fenxiao/order');
    }


    //产品列表
    public function action_product()
    {
        $products = Model_Fenxiao::get_fenxiao_product();
        foreach($products as &$product)
        {
            $nav_title = DB::select('shortname')->from('nav')->where('typeid','=',$product['id'])->and_where('issystem','=',1)->execute()->get('shortname');
            $product['modulename'] = empty($nav_title)?$product['modulename']:$nav_title;
        }
        usort($products, array("Model_Fenxiao", "product_order_cmp"));

        $this->assign('products',$products);
        $this->display('../mobile/fenxiao/product');
    }




    //我的下级分销商列表
    public function action_subfx()
    {
        $this->display('../mobile/fenxiao/subfx');
    }

    //我的下级会员，未申请成分销商
    public function action_submember()
    {
        $this->display('../mobile/fenxiao/submember');
    }

    public function action_ajax_get_submembers()
    {


        $keyword = $_POST['keyword'];

        $page = intval($_POST['page']);
        $page = $page<1?1:$page;
        $pagesize = 10;
        $offset = ($page-1)*$pagesize;

        $w = " where a.fxpcode='".$this->_fenxiao['fxcode']."' and a.status='-1' ";
        if(!empty($keyword))
        {
            $w.= " and (c.nickname like '%{$keyword}%' or c.mobile like '%{$keyword}%' or c.email like '%{$keyword}%') ";
        }

        $order_by = " order by a.fxjointime desc ";
        $sql = "select a.memberid,a.fxjointime,a.fxrankid,b.total from sline_fenxiao a
inner join sline_member c on a.memberid=c.mid
left join (select sum(amount) as total,fxmemberid from sline_fenxiao_record where memberid=".$this->_member['mid']." and type=0 group by fxmemberid) b on a.memberid=b.fxmemberid {$w} {$order_by} limit {$offset},{$pagesize}";

        $sql_num = "select count(*) as num from sline_fenxiao a inner join sline_member c on a.memberid=c.mid {$w} ";
        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        $num = DB::query(Database::SELECT,$sql_num)->execute()->get('num');

        foreach($list as &$row)
        {
            $member_info = Model_Member::get_member_byid($row['memberid']);
            $row['nickname'] = $member_info['nickname'];
            $row['litpic'] = $member_info['litpic'];
            $row['fxrank_name'] = Model_Fenxiao_Rank::get_name($row['fxrankid']);
            $row['sub_num'] = count(Model_Fenxiao::get_sub_mids($row['memberid'],1));
            $row['fxjointime'] = date('Y-m-d',$row['fxjointime']);
            $row['account'] = empty($member_info['mobile'])?$member_info['email']:$member_info['mobile'];
            $row['sub_level'] = Model_Fenxiao::get_rank($this->_member['mid'],$row['memberid']);
            $row['total'] = empty($row['total'])?0:$row['total'];
            $row['total'] = round($row['total'],2);
            $last_order_time = DB::select('addtime')->from('member_order')->where('memberid','=',$row['memberid'])->order_by('addtime','desc')->limit(1)->execute()->get('addtime');
            $row['last_order_time'] = empty($last_order_time)?'':date('Y-m-d H:i:s',$last_order_time);
        }
        echo json_encode(array('status'=>true,'list'=>$list,'total'=>$num,'page'=>$page));

    }

    //等级说明
    public function action_rank()
    {
        $next_rank = Model_Fenxiao_Rank::get_next_rank($this->_member['mid']);
        $rank_list = DB::select()->from('fenxiao_rank')->order_by('id','asc')->execute()->as_array();
        foreach($rank_list as &$rank)
        {
            $jifen_info = DB::select()->from('jifen')->where('id','=',$rank['jifen_id'])->execute()->current();
            $rank['jifen'] = empty($jifen_info['value'])?0:$jifen_info['value'];
        }
        $this->assign('next_rank',$next_rank);
        $this->assign('rank_list',$rank_list);
        $this->display('../mobile/fenxiao/rank');
    }


    //邀请好友
    public function action_invite()
    {
        $this->display('../mobile/fenxiao/invite');
    }

    //邀请卡
    public function action_invite_card()
    {
        $share_url = $this->get_share_url();
        $member_info = Model_Member_Login::check_login_info();
        $member_info = Model_Member::get_member_byid($member_info['mid']);

        $litpic = Model_Fenxiao::dowload_picture($member_info['litpic']);
        if(!empty($litpic))
        {
            $member_info['litpic'] = $litpic;
        }

        $this->assign('member',$member_info);
        $this->assign('share_url',$share_url);
        $this->display('../mobile/fenxiao/invite_card');
    }

    //邀请详情
    public function action_invite_detail()
    {
        $share_url = St_Functions::is_SSL()?'https://'.trim($GLOBALS['mobile_host'],'/\\'):'http://'.trim($GLOBALS['mobile_host'],'/\\');
        $cms_path = trim($GLOBALS['cfg_phone_cmspath'],'/\\');
        $share_url.= empty($cms_path)?'':'/'.$cms_path;
        $share_url.='/fenxiao/jieshao/joinus?fxcode='.$this->_fenxiao['fxcode'];;

        $this->assign('share_url',$share_url);
        $this->display('../mobile/fenxiao/invite_detail');
    }


    //获取我的下级分销商列表
    public function action_ajax_get_subfx()
    {
        $group = $_POST['group'];
        $order = $_POST['order'];
        $keyword = $_POST['keyword'];

        $page = intval($_POST['page']);
        $page = $page<1?1:$page;
        $pagesize = 10;
        $offset = ($page-1)*$pagesize;

        $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'],$this->_level_num);
        $first_sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'], 1);
        if($group)
        {
            $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'], $group,true);
        }

        if(empty($sub_mids))
        {
            echo json_encode(array('status'=>true,'list'=>''));
            return;
        }

        $order_by = "";
        switch($order)
        {
            case 1:
                $order_by = " order by ifnull(b.total,0) desc ";
                break;
            case 2:
                $order_by = " order by ifnull(b.total,0) asc ";
                break;
            case 3:
                $order_by = " order by a.fxjointime desc ";
                break;
            case 4:
                $order_by = " order by a.fxrankid desc ";
                break;
        }

        $w  = " where a.status=1 and a.memberid in (".implode(',',$sub_mids).")";
        if(!empty($keyword))
        {
            $w.= " and (c.nickname like '%{$keyword}%' or c.mobile like '%{$keyword}%' or c.email like '%{$keyword}%') ";
        }

        $sql = "select a.memberid,a.fxjointime,a.fxrankid,b.total from sline_fenxiao a
inner join sline_member c on a.memberid=c.mid
left join (select sum(amount) as total,fxmemberid from sline_fenxiao_record where memberid=".$this->_member['mid']." and type=0 group by fxmemberid) b on a.memberid=b.fxmemberid {$w} {$order_by} limit {$offset},{$pagesize}";

        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        foreach($list as &$row)
        {
            $member_info = Model_Member::get_member_byid($row['memberid']);
            $row['nickname'] = $member_info['nickname'];
            $row['litpic'] = $member_info['litpic'];
            $row['fxrank_name'] = Model_Fenxiao_Rank::get_name($row['fxrankid']);
            $row['sub_num'] = count(Model_Fenxiao::get_sub_mids($row['memberid'],1));
            $row['fxjointime'] = date('Y-m-d',$row['fxjointime']);
            $row['account'] = empty($member_info['mobile'])?$member_info['email']:$member_info['mobile'];
            $row['sub_level'] = Model_Fenxiao::get_rank($this->_member['mid'],$row['memberid']);
            $row['total'] = empty($row['total'])?0:$row['total'];
            $row['total'] = round($row['total'],2);

        }
        echo json_encode(array('status'=>true,'list'=>$list));
    }



    //获取产品列表, 弃用
    public function action_ajax_get_products()
    {
        set_time_limit(3000);
        $params = array();
        $params['keyword'] = $_POST['keyword'];
        $params['typeid'] = $_POST['typeid'];
        $params['ordertype'] = $_POST['ordertype'];
        $list = $this->get_products2($params);
        echo json_encode(array('status'=>true,'list'=>$list));
    }


    //已弃用
    public function get_products($params)
    {
        $typeid = intval($params['typeid']);
        $keyword = $params['keyword'];
        $pagesize = 100;
        $offset = $params['offset'];
        $number = intval($params['number']);
        $result = $this->search_products(array('typeid'=>$typeid),$keyword,$offset,$pagesize);

        $list = $result['list'];

        $list_new = array();
        $last_index = $offset;
        foreach($list as $key=>$v)
        {
            $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'],$this->_fenxiao['fxgroupid']);

            $v['commission_type'] = $commission_type;
            $min_price = $this->get_price($v['typeid'],$v['tid']);

            $v['price'] = empty($v['price'])?0:$v['price'];
            $min_price = is_array($min_price)?$min_price['price']:$min_price;
            $min_price = empty($min_price)?0:$min_price;
            $v['price'] = !empty($min_price)?$min_price:$v['price'];



            if($commission_type==1)
            {
                $commission_rate = Model_Fenxiao::get_commission_rate($v['typeid'],$v['tid'],$this->_fenxiao['fxgroupid']);
                $v['commission'] =$commission_rate[0]*100;
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['commission'] .='%';
                $v['profit'] = floor($v['price']*$commission_rate[0]);
            }
            else
            {
                $commission_cash = Model_Fenxiao::get_commission_cash($v['typeid'],$v['tid'],$this->_fenxiao['fxgroupid']);
                $v['commission'] = $commission_cash[0];
                $v['commission'] = empty($v['commission'])?0:$v['commission'];
                $v['profit'] = $v['commission'];
            }

            $last_index = $offset+$key+1;
            if(empty($v['profit']))
            {
                continue;
            }

            if(count($list_new)==$number)
            {
                if($key<(count($list)-1))
                {
                    $last_index = $last_index-1;
                }
                break;
            }
            else
            {
                $v['litpic'] = Common::img($v['litpic']);
                $list_new[] = $v;

            }
        }

        //if($key<($count()))

        $is_end = false;
        if(count($list)<$pagesize || empty($list))
        {
            $is_end = true;
        }
        return array('list'=>$list_new,'is_end'=>$is_end,'last_index'=>$last_index);
    }

    public function get_products2($params)
    {
        $typeid = intval($params['typeid']);
        $keyword = $params['keyword'];
        $ordertype = $params['ordertype'];

        $list = $this->search_products2(array('typeid'=>$typeid,'ordertype'=>$ordertype),$keyword);

        $list_new = array();

        foreach($list as $key=>$v)
        {
            $v['typeid']=  $typeid;
            $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'],$this->_fenxiao['fxgroupid']);

            $v['commission_type'] = $commission_type;
            $min_price = $this->get_price($v['typeid'],$v['tid']);

            $v['price'] = empty($v['price'])?0:$v['price'];
            $min_price = is_array($min_price)?$min_price['price']:$min_price;
            $min_price = empty($min_price)?0:$min_price;
            $v['price'] = !empty($min_price)?$min_price:$v['price'];
            $v['id'] = $v['tid'];

            //产品最低利润，按平台收入百分比时用！
            list($minprofit,$suitid)=self::get_profit_suitid($v['typeid'],$v);
            $v['minprofit'] = $minprofit;
            $v['suitid'] = $suitid;

            $v['id'] = $v['tid'];
            $v['profit'] = $this->get_prospect_fenxiao_price($typeid,$v);

            $v['litpic'] = Common::img($v['litpic']);
            $v['asdasd'] = $this->_fenxiao['fxgroupid'];
            $v['typeid'] = $typeid;
            $module_info = $row = ORM::factory('model',$v['typeid'])->as_array();
            $v['label'] = $module_info['modulename'];//标签
            $v['producttitle'] = $v['title'];//标题
            $v['series'] = Product::product_number($v['tid'], $typeid);//编号
            $v['url'] = $this->get_product_url($v['typeid'],$v['aid'],$v['webid']);//地址
            $list_new[] = $v;
        }
        return $list_new;
    }

    public static function get_profit_suitid($typeid,$v) {
        return Model_Product_Profit::get_product_profit($typeid, $v);
    }

    //已弃用
    private function search_products($params,$keyword,$offset,$pagesize)
    {
        $value_arr = array();

        //编号查询
        if (preg_match('`([a-zA-Z])(\d{3,8})`', $keyword, $preg))
        {
            $id = ltrim($preg[2],'0');

            $where = " AND a.tid='{$id}' ";
        }
        else if(is_numeric($keyword))
        {
            $result = St_Product::product_series($keyword,'',true);
            $where = " AND a.tid='{$result['id']}' and a.typeid='{$result['typeid']}' ";
        }
        else if(!empty($keyword))
        {
            //关键字查询
            $where = " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%'.$keyword.'%';
        }

        $priced_typeids = $this->_get_priced_typeids();

        $b_condition = '';
        if(!empty($priced_typeids))
        {
            $b_condition .= " or a.typeid in (".implode(',',$priced_typeids).")";
        }


        $sql = "SELECT a.* FROM `sline_search` a left join sline_fenxiao_ratio b on a.typeid=b.typeid and a.tid=b.productid and b.groupid='".$this->_fenxiao['fxgroupid']."' ";

        $sql.= "WHERE  a.ishidden=0 and a.typeid!=4 and a.typeid!=6 and (b.cash1>0 or b.fxratio1>0 {$b_condition}) {$where} ";

        //选择了栏目
        if($params['typeid'])
        {
            $sql.=" AND a.typeid='{$params['typeid']}' ";
        }




        //$sql.= "LIMIT {$offset},{$pagesize}";
        //计算总数
        $totalSql = "SELECT count(*) as dd ".strchr($sql," FROM");
        $totalSql = str_replace(strchr($totalSql,"ORDER BY"),'', $totalSql);//去掉order by

        $totalN = DB::query(1,$totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        $sql.= "LIMIT {$offset},{$pagesize}";


        $arr = DB::query(1,$sql)->parameters($value_arr)->execute()->as_array();
        foreach($arr as &$v)
        {

            $module_info = $row = ORM::factory('model',$v['typeid'])->as_array();
            $typeid = $v['typeid']<10 ? '0'.$v['typeid'] : $v['typeid'];
            $v['label'] = $module_info['modulename'];//标签
            $v['producttitle'] = $v['title'];//标题
            $v['series'] = Product::product_number($v['tid'], $typeid);//编号
            $v['url'] = $this->get_product_url($v['typeid'],$v['aid'],$v['webid']);//地址
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr
        );
        return $out;
    }

    //获取产品，必须要有tid 和 typeid
    private function search_products2($params,$keyword)
    {
        $value_arr = array();
        //编号查询
        $where = " where a.ishidden=0 ";

        if(is_numeric($keyword))
        {
            $result = St_Product::product_series($keyword,'',true);
            $where .= " AND a.id='{$result['id']}'";
        }
        else if(!empty($keyword))
        {
            //关键字查询
            $where .= " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%'.$keyword.'%';
        }

        $typeid = $params['typeid'];
        $table = $this->get_table($typeid);

        if(empty($table))
        {
            return array(
                'total' => 0,
                'list' => null
            );
        }

        if($table == 'model_archive')
        {
            $where.=" AND a.typeid={$typeid} ";
        }
        if($table == 'tuan')
        {
            $endtime = time();
            $where.=" AND a.ishidden=0 and endtime > {$endtime} ";
        }else{
            $where.=" AND a.ishidden=0 ";
        }
        $order = " order by ifnull(b.displayorder,999999) asc,b.cash1 desc ";
        if($params['ordertype']==1)
        {
            $order = " order by a.modtime desc,ifnull(b.displayorder,999999) asc ";
        }

        $sql = " select a.title,a.supplierlist,a.litpic,a.webid,a.id as tid,a.aid,a.modtime,a.price,b.* from sline_{$table} a left join sline_fenxiao_ratio  b on a.id=b.productid and b.typeid={$typeid} and b.groupid=".$this->_fenxiao['fxgroupid']." {$where} {$order} ";
        $sql.= "LIMIT 0,100";

        $arr = DB::query(1,$sql)->parameters($value_arr)->execute()->as_array();
        return $arr;
    }

    //获取已设置佣金或报价的产品
    private function _get_priced_typeids()
    {
        static $_priced_typeids = array();

        if(!empty($_priced_typeids))
        {
            return $_priced_typeids;
        }

        $result = DB::query(Database::SELECT,"select * from sline_fenxiao_config where (varname like 'cfg_fenxiao_commission_type_%' or varname like 'cfg_fenxiao_first_cash_%' or varname like 'cfg_fenxiao_first_ratio_%') and groupid='".$this->_fenxiao['fxgroupid']."'")->execute()->as_array();
        $set_info = array();
        foreach($result as $row)
        {
            $set_info[$row['varname']] = $row['value'];
        }

        foreach($set_info as $k=>$v)
        {
            if(strpos($k,'cfg_fenxiao_commission_type_')!==false)
            {
                $typeid = str_replace('cfg_fenxiao_commission_type_','',$k);
                if($v==0 && $set_info['cfg_fenxiao_first_cash_'.$typeid]>0)
                {
                    $_priced_typeids[] = $typeid;
                }
                else if($v==1 && $set_info['cfg_fenxiao_first_ratio_'.$typeid]>0)
                {
                    $_priced_typeids[] = $typeid;
                }
            }
        }
        return $_priced_typeids;
    }

    private function  get_product_url($typeid,$aid,$webid)
    {
        $module = ORM::factory('model',$typeid);
        $pinyin = $module->pinyin;
        $correct = $module->correct;
        $py = empty($correct)?$pinyin:$correct;//($typeid>17 || $typeid==8 || $typeid==13) ? $pinyin : $correct;
        $url = Common::get_web_url($webid);
        $url.="/$py/show_{$aid}.html";
        return $url;
    }






    //获取分销订单
    public function action_ajax_get_orders()
    {
        $rank = intval($_POST['rank']);
        $typeid = intval($_POST['typeid']);
        $status = $_POST['status'];
        $order = $_POST['order'];
        $keyword = $_POST['keyword'];

        $page = intval($_POST['page']);
        $page = $page<1?1:$page;
        $pagesize = 10;
        $offset = ($page-1)*$pagesize;

        $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'],$this->_level_num);

        if(!empty($rank))
        {
            // 自购订单
            if($rank == '4')
            {
                $sub_mids = $this->_member['mid'];
                $w = " where a.memberid in ($sub_mids) ";
            }
            else
            {
                $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'],$rank,true);
                $w = " where a.memberid in (".implode(',',$sub_mids).") ";
            }
        }
        else
        {
            $sub_mids[] = $this->_member['mid'];
            $w = " where a.memberid in (".implode(',',$sub_mids).") ";
        }
        if(!empty($sub_mids) && !empty($keyword))
        {

            $keyword_submids = Model_Fenxiao::get_keyword_sub_mids($keyword);
            $keyword_w = !empty($keyword_submids)? " or mid in (".implode(',',$keyword_submids).")":'';

            $sub_members = DB::query(Database::SELECT,"select mid from sline_member where mid in(".implode(',',$sub_mids).") and (mobile like '%{$keyword}%' or email like '%{$keyword}%' or nickname like '%{$keyword}%' {$keyword_w})")->execute()->as_array();
            $sub_mids = array();
            foreach($sub_members as $sub_member)
            {
                if(!empty($sub_member['mid']))
                {
                    $sub_mids[] = $sub_member['mid'];
                }
            }
        }

        if(empty($sub_mids))
        {
            echo json_encode(array('status'=>true,'list'=>''));
            return;
        }


        if(!empty($typeid))
        {
            $w.=" and a.typeid={$typeid} ";
        }

        if(!empty($status) || $status===0 || $status==='0')
        {
            $w.=" and a.status='{$status}' ";
        }

        $order_by = "";
        switch($order)
        {
            case 2:
                $order_by = " order by ifnull(b.amount,0) desc,a.addtime desc ";
                break;
            case 3:
                $order_by = " order by ifnull(b.amount,0) asc,a.addtime desc ";
                break;
            default:
                $order_by = " order by a.addtime desc";
        }

        $sql = " select a.*,b.amount as fenxiao_amount from sline_member_order a left join sline_fenxiao_record b on a.id=b.orderid and (b.memberid is null or b.memberid=".$this->_member['mid'].") {$w} {$order_by} limit {$offset},{$pagesize}";

        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();

        foreach ($list as &$v)
        {
            $model = ORM::factory('model', $v['typeid']);
            $table = $model->maintable;
            if ($table)
            {
                $py = empty($model->correct) ? $model->pinyin : $model->correct;
                $info = ORM::factory($table, $v['productautoid'])->as_array();
                $out = $info;
                $v['litpic'] = Common::img($out['litpic']);
                $v['url'] = St_Functions::get_web_url($info['webid']) . "/{$py}/show_{$info['aid']}.html";
            }
            $v['totalprice'] = Model_Member_Order::order_total_price($v['id'],$v);

            $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$v['typeid'],$this->_fenxiao['fxgroupid']);
            $rank = Model_Fenxiao::get_rank($this->_member['mid'],$v['memberid']);
            $rank_index=$rank;
            $v['commission_type'] = $commission_type;




            /* if($commission_type==1)
             {
                 $commission_rate = Model_Fenxiao::get_commission_rate($v['typeid'],$v['productautoid'],$this->_fenxiao['fxgroupid']);
                 $v['commission'] =$commission_rate[$rank_index]*100;
                 $v['commission'] = empty($v['commission'])?0:$v['commission'];
                 $v['commission'] .='%';
             }
             else
             {
                 $commission_cash = Model_Fenxiao::get_commission_cash($v['typeid'],$v['productautoid'],$this->_fenxiao['fxgroupid']);
                 $v['commission'] = $commission_cash[$rank_index];
                 $v['commission'] = empty($v['commission'])?0:$v['commission'];
             }*/

            $order_temp = Model_Member_Order::order_info($v['ordersn']);
            $commission_info = Model_Fenxiao::get_order_fenxiao_info($order_temp);

            if(empty($rank_index))
            {
                $v['commission_amount'] = number_format(floatval($commission_info['commission']),2);
            }
            else
            {
                $v['commission_amount'] = number_format(floatval($commission_info['commission'.$rank_index]),2);
            }

            $member_info = Model_Member::get_member_byid($v['memberid']);
            $v['member'] = $member_info;

            $parent_fenxiao = Model_Fenxiao::get_ancestor_fenxiao($v['memberid'],1);
            $v['parent_member'] = Model_Member::get_member_byid($parent_fenxiao['memberid']);

            $v['addtime'] = date('Y-m-d H:i',$v['addtime']);
            $v['fenxiao_amount'] = empty($v['fenxiao_amount']) ? 0 : number_format($v['fenxiao_amount'],2);
            $v['status_name'] = Model_Member_Order::get_status_name($v['status']);
        }
        echo json_encode(array('status'=>true,'list'=>$list));
    }

    //获取今天的佣金
    private function get_today_commission()
    {
        $memberid=$this->_member['mid'];
        $starttime=strtotime(date('Y-m-d'));
        $sql="select sum(ifnull(amount,0)) as totalamount from sline_fenxiao_record where type=0 and memberid={$memberid} and addtime>{$starttime}";
        $amount=DB::query(Database::SELECT,$sql)->execute()->get('totalamount');
        $amount=empty($amount)?0:$amount;
        return $amount;
    }
    //获取销售总额
    private function get_total_sale($istoday=false)
    {
        $memberid=$this->_member['mid'];
        if(!$istoday)
            $sql="select * from sline_member_order a inner join sline_fenxiao_record b on a.id=b.orderid where b.type=0 and b.memberid={$memberid}";
        else
        {
            $starttime=strtotime(date('Y-m-d'));
            $sql = "select * from sline_member_order a inner join sline_fenxiao_record b on a.id=b.orderid where b.type=0 and b.memberid={$memberid} and b.addtime>={$starttime}";
        }
        $list=DB::query(Database::SELECT,$sql)->execute()->as_array();
        $amount=0;
        foreach($list as $row)
        {
            $amount+=Model_Member_Order::get_payed_amount($row);
        }
        return $amount;
    }



    public function action_myorder()
    {
        $type=$_GET['type'];
        $this->assign('type',$type);
        $this->display('myorder');
    }
    /* public function action_ajax_getorder()
     {
         $memberid=$this->_member['mid'];
         $page=intval($_POST['page']);
         $page=empty($page)?1:$page;
         $pageSize=10;
         $start=($page-1)*$pageSize;
         $type=$_POST['type'];
         $subMemberids=Model_Fenxiao::get_sub_mids($memberid);

         if(empty($subMemberids))
         {
             echo json_encode(array('status'=>true,'data'=>null));
             return;
         }


         $w=" where memberid in (".implode(',',$subMemberids).")";
         if(!empty($type))
         {
             $w.=$type==1?' and status=1':' and (status=2 or status=5)';
         }



         $sql="select * from sline_member_order $w order by addtime desc limit $start,$pageSize";
         $list=DB::query(Database::SELECT,$sql)->execute()->as_array();
         foreach($list as &$row)
         {
             $row['statusname']= Model_Member_Order::get_status_name($row['status']);
             $row['totalamount']= Model_Member_Order::get_payed_amount($row);
         }
         echo json_encode(array('status'=>true,'data'=>$list));
     }
    */
    public function action_ajax_getsubmember()
    {
        $memberid=$this->_member['mid'];
        $fenxiao=Model_Fenxiao::check_fenxiao($memberid,false);
        if(!$fenxiao)
        {
            return;
        }
        $page=intval($_POST['page']);
        $keyword = $_POST['keyword'];

        $page=empty($page)?1:$page;
        $pageSize=10;
        $start=($page-1)*$pageSize;
        $type=$_POST['type'];
        $member_fields='b.mid,b.nickname,b.sex,b.mobile,b.email,b.litpic,b.jointime,b.regtype';

        if(empty($type))
        {
            $w=" where a.id is not null";
            $w.=" and a.fxpcode='{$fenxiao['fxcode']}'";
            if(!empty($keyword))
            {
                $w.= " and (b.nickname like '%{$keyword}%' or b.mobile like '%{$keyword}%' or b.email like '%{$keyword}%') ";
            }
            $sql="select a.*,$member_fields from sline_fenxiao a inner join sline_member b on a.memberid=b.mid $w order by a.fxjointime desc limit {$start},{$pageSize}";
        }
        /*else if($type==2)
        {
            $fxcodeArr=Model_Fenxiao::get_sub_fxcode($fenxiao['fxcode'],0);
            if(!empty($fxcodeArr))
            {
                foreach($fxcodeArr as &$v)
                {
                    $v="'".$v."'";
                }
                $w="where a.fxpcode in (".implode(',',$fxcodeArr).")";
                $sql="select a.*,$member_fields from sline_fenxiao a inner join sline_member b on a.memberid=b.mid $w order by a.fxjointime desc limit {$start},{$pageSize}";
            }
        }
        else if($type==3)
        {
            $fxcodeArr=Model_Fenxiao::get_sub_fxcode($fenxiao['fxcode'],2);
            if(!empty($fxcodeArr))
            {
                foreach($fxcodeArr as &$v)
                {
                    $v="'".$v."'";
                }
                $w="where a.fxpcode in (".implode(',',$fxcodeArr).")";
                $sql="select a.*,$member_fields from sline_fenxiao a inner join sline_member b on a.memberid=b.mid $w order by a.fxjointime desc limit {$start},{$pageSize}";
            }
        }*/

        if(empty($sql))
        {
            echo json_encode(array('status'=>false,'msg'=>'数据不存在'));
        }else {
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as &$row)
            {
                $member_info = Model_Member::get_member_byid($row['memberid']);
                $row['litpic']=empty($row['litpic'])? $GLOBALS['cfg_res_url'].'/images/headerimg.png' :$row['litpic'];
                $row['jointime'] = date('Y-m-d',$row['fxjointime']);
                $row['totalamount'] = Model_Fenxiao::get_consume_amount($row['memberid']);
                $row['account'] = empty($member_info['mobile'])?$member_info['email']:$member_info['mobile'];
            }
            echo json_encode(array('status'=>true,'msg'=>'获取成功','data'=>$list));
        }
    }
    public function action_joinus()
    {

        $this->display('../mobile/fenxiao/joinus');
    }
    public function action_joinus_save()
    {
        $memberid=$this->_member['mid'];
        $autoverify=Model_Fenxiao_Config::get_val('cfg_fenxiao_autoverify');
        Model_Fenxiao::joinus($memberid);

        $fenxiaoModel=ORM::factory('fenxiao')->where('memberid','=',$memberid)->find();

        if($autoverify==0 && $fenxiaoModel->status==0)
        {
            $this->request->redirect('fenxiao/joinverifying');
            return;
        }
        if($fenxiaoModel->status==2)
        {
            $fenxiaoModel->status=0;
            $fenxiaoModel->save();
            $this->request->redirect('fenxiao/joinverifying');
            return;
        }
        if($autoverify==1 && $fenxiaoModel->status==0)
        {
            $fenxiaoModel->status=1;
            $fenxiaoModel->verifytime=time();
            $fxrankid = Model_Fenxiao::get_rankid($this->_member['mid']);
            $fenxiaoModel->fxrankid=$fxrankid;
            $fenxiaoModel->save();
        }
        $this->request->redirect('fenxiao/joinsuccess');
    }
    public function action_jieshao()
    {
        $content = Model_Fenxiao_Config::get_val('cfg_fenxiao_content');
        $this->assign('content',$content);
        $this->display('../mobile/fenxiao/jieshao');
    }
    //已申请 成功，在未开启审核的情况下
    public function action_joinsuccess()
    {
        $this->display('../mobile/fenxiao/joinsuccess');
    }
    //请等待审核
    public function action_joinverifying()
    {
        $this->display('../mobile/fenxiao/joinverifying');
    }
    //请等待审核
    public function action_joinrefused()
    {
        $this->display('../mobile/fenxiao/joinrefused');
    }
    public function action_joinfrozen()
    {
        $this->display('../mobile/fenxiao/joinfrozen');
    }
    public function action_joinapplyunfrozen()
    {
        // $this->display('joinapplyunfrozen');
    }
    public function action_qrcode()
    {
        /*$m_host = DB::select('value')->from('sysconfig')->where('varname','=','cfg_m_main_url')->execute()->get('value');
        $m_host = str_replace('http://','',$m_host);
        $m_host = str_replace('https:://','',$m_host);
        $m_host = trim($m_host,'\\../');
        $m_full_host='';
        if($m_host==$_SERVER['HTTP_HOST'] || empty($m_host))
        {
            $m_full_host='http://'.$m_host.'/phone';
        }
        else
        {
            $m_full_host='http://'.$m_host;
        }
        $fxcode = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$this->_member['mid'])->execute()->get('fxcode');
        $url = $m_full_host.'/member/register?fxcode='.$fxcode;*/
        $ticket = Weixin::get_ticket($this->_member['mid']);
        $this->assign('ticket',$ticket);
        $this->display('qrcode');
    }
    public function action_share()
    {

        Model_Fenxiao::check_fenxiao($this->_member['mid'],true);
        $url=urldecode($_GET['url']);

        $match=array();
        preg_match("/[\\\\\/]{1}([a-z]+)[\\\\\/]{1}show_([0-9]+)/i",$url,$match);

        $module_name = $match[1];
        $aid = $match[2];
        $model = DB::select()->from('model')->where('correct','=',$module_name)->or_where('modulename','=',$module_name)->execute()->current();
        if(!empty($model))
        {
            $litpic = DB::select('litpic')->from($model['maintable'])->where('aid','=',$aid)->execute()->get('litpic');
            $share_pic = !empty($litpic)?$GLOBALS['cfg_basehost'].$litpic:'';
            $this->assign('share_pic',$share_pic);
        }


        $content=urldecode($_GET['content']);
        $encodeurl=urlencode($url);
        $this->assign('url',$url);
        $this->assign('encodeurl',$encodeurl);
        $this->assign('content',$content);
        $this->display('share');
    }
    public function action_ajax_get_weixininfo()
    {
        $url=$_POST['url'];
        $cfg_wx_appid=Model_Fenxiao_Config::get_val('cfg_fenxiao_wx_appid');
        $cfg_wx_appsecret=Model_Fenxiao_Config::get_val('cfg_fenxiao_wx_appsecret');

        $result=file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$cfg_wx_appid}&secret={$cfg_wx_appsecret}");
        try {
            if(!$result)
                throw new Exception("未能获取微信token");
            $result = json_decode($result, true);
            $accessToken = $result['access_token'];
            if(!$accessToken)
                throw new Exception('未能获取微信token');
            $ticketResult = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=jsapi");
            $ticketResult = json_decode($ticketResult,true);
            $ticket=$ticketResult['ticket'];
            if(!$ticket)
                throw new Exception('未能获取微信ticket');
            $noncestr = $this->get_wx_noncestr();
            $timestamp = time();
            $queryArr=array('jsapi_ticket'=>$ticket,'noncestr'=>$noncestr,'timestamp'=>$timestamp,'url'=>$url);
            $queryStr='';
            foreach($queryArr as $k=>$v)
            {
                $queryStr.=$k.'='.$v.'&';
            }
            $queryStr=substr($queryStr,0,-1);
            $signature=sha1($queryStr);
            $data=array('appid'=>$cfg_wx_appid,'ticket'=>$ticket,'noncestr'=>$noncestr,'timestamp'=>$timestamp,'signature'=>$signature);
            echo json_encode(array('status'=>true,'msg'=>'获取成功','data'=>$data));

        }catch (Exception $excep)
        {
            echo json_encode(array('status'=>false,'msg'=>$excep->getMessage()));
        }

    }
    private function get_wx_noncestr()
    {
        $charStr='abcdefghijklmnopqrstuvwxyz123456789';
        $len=strlen($charStr)-1;
        $str='';
        for($i=0;$i<10;$i++)
        {
            $index=mt_rand(0,$len);
            $str.=$charStr[$index];
        }
        return $str;
    }


    public function action_logout()
    {
        Common::session('member',null);
        header("location:/");
        exit;
    }

    //获取某个产品的最低价
    private function get_price($typeid,$productid)
    {
        $model_info = DB::select()->from('model')->where('id','=',$typeid)->execute()->current();

        $maintable = $model_info['maintable'];
        $letter_arr = explode('_',$maintable);
        foreach($letter_arr as &$letter)
        {
            $letter = ucfirst($letter);
        }
        $class_name='Model_'.implode('_',$letter_arr);
        $price = 0;
        if(class_exists($class_name)&& method_exists($class_name,'get_minprice') )
        {
            $price = call_user_func(array($class_name, 'get_minprice'),$productid);
        }
        return $price;
    }
    /*
    private function check_fenxiao($redirect=true)
    {
        $fxModel=ORM::factory('fenxiao')->where('memberid','=',$this->_member['mid'])->find();
        $memberModel=ORM::factory('member',$this->_member['mid']);
        if(!$fxModel->loaded())
        {
            if(!$redirect)
                return false;
            $this->request->redirect('index/joinus');
            return;
        }
        $autoverify=Model_Fenxiao_Config::get_val('cfg_fenxiao_autoverify');

        if($fxModel->status==0 && $autoverify==1)
        {
            $this->request->redirect('index/joinus');
            return;
        }
        if($fxModel->status==0 && $autoverify==0)
        {
            $this->request->redirect('index/joinverifying');
            return;
        }
        if($fxModel->status==2)
        {
            $this->request->redirect('index/joinrefused');
            return;
        }

        if($fxModel->isfrozen==0)
        {
            $autofreeze=Model_Fenxiao_Config::get_val('cfg_fenxiao_autofreeze');
            $freezeduration=floatval(Model_Fenxiao_Config::get_val('cfg_fenxiao_freeze_duration'));
            if($autofreeze==1&&$freezeduration>0&& $fxModel->fxlogintime>0)
            {
                $curtime=time();
                $durationSeconds=$freezeduration*3600;

               if($fxModel->fxlogintime+$durationSeconds<$curtime)
               {
                   $fxModel->isfrozen=1;
               }
                $fxModel->fxlogintime=$curtime;
                $fxModel->save();
            }
        }
        if($fxModel->isfrozen==1)
        {
            $this->request->redirect('index/joinfrozen');
            return;
        }
        return $fxModel->as_array();
    }
  */
    //获取返佣总和
    private function get_total_profit()
    {
        $memberid=$this->_member['mid'];
        $result = DB::query(Database::SELECT,"select amount from sline_fenxiao_record where memberid='{$memberid}' and type=0")->execute()->as_array();
        $amount = 0;
        foreach($result as $row)
        {
            $amount+=$row['amount'];
        }
        return $amount;
    }

    //获取已付款，但未返佣的佣金总和
    private function get_total_unfinish_profit()
    {
        $userid = $this->_member['mid'];
        $sql = "SELECT a.* FROM sline_fenxiao_data AS a ";
        $sql.= "LEFT JOIN sline_member_order AS b ON(a.order_id=b.id) ";
        $sql.= "WHERE (a.memberid={$userid} OR a.memberid1={$userid} OR a.memberid2={$userid} OR a.memberid3={$userid}) ";
        $sql.= "AND b.status=2 ";
        $order = DB::query(1, $sql)->execute()->as_array();
        if(count($order)<1){
            return 0;
        }
        $info = array(
            0 => array(),//自购订单
            1 => array(),//下1级分销订单
            2 => array(),//下2级分销订单
            3 => array(),//下3级分销订单
        );

        foreach ($order as $v){
            if($v['memberid']==$userid){
                array_push($info[0],$v['order_id']);
            }
            if($v['memberid1']==$userid){
                array_push($info[1],$v['order_id']);
            }
            if($v['memberid2']==$userid){
                array_push($info[2],$v['order_id']);
            }
            if($v['memberid3']==$userid){
                array_push($info[3],$v['order_id']);
            }
        }
        $total = 0;
        foreach ($info as $k=>$v){
            if(count($v)>0){
                $order_id = implode(',',$v);
                $sum_sql = $k<1?"sum(fx_self) as price":"sum(fx_top{$k}) as price";
                $price = DB::select(DB::expr($sum_sql))->from('member_order_compute')->where("order_id IN({$order_id})")->execute()->get('price');
                $total = bcadd($total,$price,2);
            }
        }
        return $total;
    }

    //获取返佣定单总数
    private function get_order_number()
    {
        $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'],$this->_level_num);
        if(empty($sub_mids))
        {
            return 0;
        }
        $num = DB::query(Database::SELECT,"select count(*) as num from sline_member_order where memberid in (".implode(',',$sub_mids).")")->execute()->get('num');
        return $num;
    }
    //获取下级会员数
    private function get_member_num($is_member=0)
    {
        $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'],$this->_level_num);
        $num=0;
        if(empty($sub_mids))
        {
            return 0;
        }
        if($is_member==0)
        {
            $num = DB::query(Database::SELECT,"select count(*) as num from sline_fenxiao where memberid in (".implode(',',$sub_mids).") and status=1")->execute()->get('num');
        }
        else
        {
            $sub_mids = Model_Fenxiao::get_sub_mids($this->_member['mid'],1);
            $num = DB::query(Database::SELECT,"select count(*) as num from sline_fenxiao where memberid in (".implode(',',$sub_mids).") and status=-1")->execute()->get('num');
        }
        return $num;

    }
    private function get_share_url()
    {
        $share_url = St_Client::get_http_protocol().trim($GLOBALS['mobile_host'],'/\\');
        $cms_path = trim($GLOBALS['cfg_phone_cmspath'],'/\\');
        $share_url.= empty($cms_path)?'':'/'.$cms_path;
        $share_url.='/fenxiao/jieshao/joinus?fxcode='.$this->_fenxiao['fxcode'];
        return $share_url;
    }

    //获取表名
    private function get_table($typeid)
    {
        $model=ORM::factory('model',$typeid);
        if(!$model->loaded())
            return false;
        return $model->maintable;
    }

    //和Controller_Mobile_Fenxiao_Jieshao的函数一致
    private function get_prospect_fenxiao_price($typeid,$product)
    {
        $fenxiao = $this->_fenxiao;
        $fxgroupid=$fenxiao['fxgroupid'];

        $commission_type=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid,$fxgroupid);
        $min_price = self::get_price($typeid,$product['id']);

        $product['price'] = empty($product['price'])?0:$product['price'];
        $min_price = is_array($min_price)?$min_price['price']:$min_price;
        $min_price = empty($min_price)?0:$min_price;
        $product['price'] = !empty($min_price)?$min_price:$product['price'];

        if($commission_type==1)
        {
            $commission_rate = Model_Fenxiao::get_commission_rate($typeid,$product['id'],$fxgroupid);
            $profit =number_format($product['price']*$commission_rate[0],2);
        }
        else if($commission_type==2)
        {
//            $commission_rate = Model_Fenxiao::get_commission_rate_platform($typeid,$product['id'],$fxgroupid);
//            $temp_order = array('typeid'=>$typeid,'productautoid'=>$product['id'],'totalprice'=>$product['price'],'dingnum'=>1);
//            if($typeid==5)
//            {
//                $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
//            }
//            else
//            {
//                $platform_price = empty($product['supplierlist']) ? $product['price'] : Model_Member_Order_Compute::caculate_platform_commission($temp_order);
//            }
//
//            $profit = number_format($platform_price*$commission_rate[0],2);
            $commission_rate = Model_Fenxiao::get_commission_rate_platform(
                $typeid,
                $product['id'],
                $fxgroupid
            );
            $v['commission'] = $commission_rate[0] * 100;
            $v['commission'] = empty($v['commission']) ? 0 : $v['commission'];
            $v['commission'] .= '%';
            $temp_order = array(
                'typeid' => $typeid,
                'productautoid' =>  $product['id'],
                'suitid' => $product['suitid'],
                'totalprice' => $product['price'],
                'channel_id' => 1,
                'dingnum' => 1
            );
            $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
            if($platform_price['settlement_type']==2){//销售价-获取销售最低价
                $platform_price =  $product['price'];
            }else{//结算价模式-获取最低利润报价
                $platform_price = $product['minprofit'];
            }
            $profit = $platform_price * $commission_rate[0];
        }
        else
        {
            $commission_cash = Model_Fenxiao::get_commission_cash_line($typeid,$product['id'],$fxgroupid);
            if($typeid==1){
                $time = strtotime(date('Y-m-d',time()));
                //取该产品的今天有报价的那1个套餐
                $sql_suit="select propgroup from sline_line_suit_price where day>=".$time.' and lineid = '.$product['id'].' order by suitid asc';
                $suit_data = DB::query(1,$sql_suit)->execute()->current();
                //2:成人 1:小孩 3:老人,4:人群四，5：人群五，6：人群6
                //假如报了儿童，就在佣金设置里面找儿童的收益
                $people_relationship = [
                    1 => 'child',
                    2 => 'adult',
                    3 => 'old',
                    4 => 'people4',
                    5 => 'people5',
                    6 => 'people6',
                ];
                $_profit = [];
                //如果有报价
                if($suit_data['propgroup']){
                    $propgroup = explode(',',$suit_data['propgroup']);//该套餐的报价人群
                    foreach ($propgroup as $propgroup_v) {
                        if(isset($people_relationship[$propgroup_v])){
                            $_people = $people_relationship[$propgroup_v];//报价人群
                            $_profit[] = $commission_cash[0][$_people];
                        }
                    }
                }
                $profit = number_format(max($_profit),2);//金额最大的
            }else{
                $profit =number_format($commission_cash[0]['adult'],2);
            }
        }
        return $profit;
    }


}

